﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CodePlex.Resourceful.Microsoft.Azure
{
    public class AzureQueueClient : BaseAzureClient
    {

        public static readonly string Version = "2009-04-14";

        public AzureQueueClient(string accountName, string base64key)
            : this(accountName, base64key, true)
        {
        }

        public AzureQueueClient(string accountName, string base64key,bool useSSL)
            : this(accountName, base64key, AzureConstants.PublicQueueServiceHost, false, useSSL)
        {
        }

        public AzureQueueClient(string accountName, string base64key, string serviceHost, bool usePathStyle, bool useSSL)
            : base(accountName, base64key,serviceHost,usePathStyle,useSSL,Version)
         {
         }





        public ClientResponse GetQueues( string prefix, string marker, int? maxResults)
        {

            // GET http://myaccount.queue.core.windows.net?comp=list

            /*  prefix: Filters the results to return only queues whose name begins with the specified prefix.
             * 
             * marker: A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items.

                The marker value is opaque to the client.
             * 
             * maxresults: Specifies the maximum number of queues to return. If maxresults is not specified, the server will return up to 5,000 items.
             * */


            NameValuePairs pathParameters = new NameValuePairs();
            if (prefix != null)
            {
                pathParameters["prefix"] = prefix;
            }
            if (marker != null)
            {
                pathParameters["marker"] = marker;
            }
            if (maxResults != null)
            {
                pathParameters["maxresults"] = maxResults.Value.ToString();
            }

            return DoAzureRequest(HttpMethod.Get, "", "list", pathParameters, null);

        }


        public ClientResponse PutQueue(string queueName, NameValuePairs metadata)
        {
            metadata = metadata ?? new NameValuePairs();

            NameValuePairs headers = new NameValuePairs();
            foreach (string key in metadata.Keys)
            {
                headers.Add(AzureConstants.Headers.MicrosoftMetaPrefix + key, metadata[key]);
            }

            // PUT http://myaccount.queue.core.windows.net/myqueue HttpStatus.Created,
            return DoAzureRequest(HttpMethod.Put, queueName, null, null, headers);
        }

        public ClientResponse DeleteQueue(string queueName)
        {
            // DELETE http://myaccount.queue.core.windows.net/myqueue  HttpStatus.NoContent, 
            return DoAzureRequest(HttpMethod.Delete, queueName, null, null, null);
        }

        public ClientResponse HeadQueue(string queueName)
        {
            // GET/HEAD http://myaccount.queue.core.windows.net/myqueue?comp=metadata
            return DoAzureRequest(HttpMethod.Head, queueName, "metadata", null, null);
        }

        public ClientResponse PutQueueMetadata(string queueName, NameValuePairs metadata)
        {
            // PUT http://myaccount.queue.core.windows.net/myqueue?comp=metadata
            return DoAzureRequest(HttpMethod.Put, queueName, "metadata", null, MetadataToHeaders(metadata));

        }





        public ClientResponse DeleteMessages(string queueName)
        {
            // DELETE http://myaccount.queue.core.windows.net/myqueue/messages  HttpStatus.NoContent, 
            return DoAzureRequest(HttpMethod.Delete, queueName + "/messages", null, null, null);
        }



        public ClientResponse GetMessagesPeekOnly(string queueName, int? numMessages)
        {
            //  numofmessages Optional. A nonzero integer value that specifies the number of messages to peek from the queue, up to a maximum of 32. By default, a single message is peeked from the queue with this operation.

            NameValuePairs pathParameters = new NameValuePairs();
            pathParameters["peekonly"] = "true";
            if (numMessages != null)
            {
                pathParameters["numofmessages"] = numMessages.ToString();
            }
          
            // GET http://myaccount.queue.core.windows.net/myqueue/messages?peekonly=true
            return DoAzureRequest(HttpMethod.Get, queueName + "/messages", null, pathParameters, null);

        }



        public ClientResponse GetMessages(string queueName, int? numMessages, int? visibilityTimout)
        {

            // numofmessages:    Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. 
            //   By default, a single message is retrieved from the queue with this operation.

            // visibilitytimeout:  Optional. An integer value that specifies the message's visibility timeout in seconds. 
            // The maximum value is 2 hours. The default message visibility timeout is 30 seconds.


            NameValuePairs pathParameters = new NameValuePairs();
            if (numMessages != null)
            {
                pathParameters["numofmessages"] = numMessages.ToString();
            }
            if (visibilityTimout != null)
            {
                pathParameters["visibilitytimeout"] = visibilityTimout.ToString();
            }
           

            // GET http://myaccount.queue.core.windows.net/myqueue/messages  HttpStatus.OK, 
            return DoAzureRequest(HttpMethod.Get, queueName + "/messages", null, pathParameters, null);
        }

        public ClientResponse PostMessage(string queueName, string messageText, int? messageTTLSeconds )
        {

            // messagettl=int-seconds  Optional. Specifies the time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days.


            NameValuePairs pathParameters = new NameValuePairs();
            if (messageTTLSeconds != null)
            {
                pathParameters["messagettl"] = messageTTLSeconds.ToString();
            }
           
string messageXml = string.Format(@"<QueueMessage>
    <MessageText>{0}</MessageText>
</QueueMessage>",messageText);

            

            // POST http://myaccount.queue.core.windows.net/myqueue/messages
            return this.DoAzureRequest(HttpMethod.Post, queueName + "/messages", null, pathParameters, null, true, Utils.ToStream(messageXml), null);

        }


        public ClientResponse DeleteMessage(string queueName, string messageID, string popReceipt)
        {

            //  popreceipt Required. A valid pop receipt value returned from an earlier call to the Get Messages operation.

            NameValuePairs pathParameters = new NameValuePairs();
            pathParameters["popreceipt"] = popReceipt;

            // DELETE http://myaccount.queue.core.windows.net/myqueue/messages/messageid?popreceipt=string-value  HttpStatus.NoContent, 
            return DoAzureRequest(HttpMethod.Delete, queueName + "/messages/" + messageID, null, pathParameters, null);
        }


    }

}
